package com.szh.taobaounion.Presenter.impl;

import com.szh.taobaounion.Presenter.IHomePresenter;
import com.szh.taobaounion.model.Api;
import com.szh.taobaounion.model.domain.CateGories;
import com.szh.taobaounion.utils.LogUtils;
import com.szh.taobaounion.utils.RetrofitManager;
import com.szh.taobaounion.view.IHomeCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterImpl implements IHomePresenter {
    private IHomeCallBack mCallBack=null;

    @Override
    public void getCattgories() {
        if (mCallBack != null) {
            mCallBack.onLoading();
        }
    //加载分类内容
        Retrofit retrofit = RetrofitManager.getInstance().getmRetrofit();
        Api api = retrofit.create(Api.class);
        Call<CateGories> task = api.getCategories();
        task.enqueue(new Callback<CateGories>() {
            @Override
            public void onResponse(Call<CateGories> call, Response<CateGories> response) {
                //数据结果
                int code = response.code();
                LogUtils.d(HomePresenterImpl.this,"result code is  "+code);

                if (code== HttpURLConnection.HTTP_OK) {
                    //请求成功
                    CateGories categories = response.body();
                    LogUtils.d(HomePresenterImpl.this,categories.toString());
                    if (mCallBack != null) {
                    if (categories==null||categories.getData().size()==0) {
                           mCallBack.onEmpty();
                    }else {
                        mCallBack.onCategoriesLoaded(categories);
                    }
                    }
                }else {
                    //请求失败
                     LogUtils.i(this,"请求失败");
                    if (mCallBack != null) {
                        mCallBack.onError();
                    }
                }
            }

            @Override
            public void onFailure(Call<CateGories> call, Throwable t) {
              //加载失败的结果
                LogUtils.e(this,"请求错误"+t);
                if (mCallBack != null) {
                    mCallBack.onError();
                }
            }
        });
    }

    @Override
    public void registerViewCallBack(IHomeCallBack callBack) {
         this.mCallBack=callBack;
    }

    @Override
    public void unregisterViewCallBack(IHomeCallBack callBack) {
          mCallBack=null;
    }
}
